package com.dayatang.spring;



import javax.annotation.Resource;
import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.junit.Before;
import org.junit.BeforeClass;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;

import com.dayatang.domain.InstanceFactory;
import com.dayatang.spring.factory.SpringProvider;

/**
 * Business模块的基础测试支持类
 * 利用Spring Test Framework提供的功能,自动绑定本模块的applicationContext
 * 子类中可以直接使用applicationContext
 * @author Alva
 *
 */
@ContextConfiguration(locations={"classpath:spring/*.xml"})
public class BaseSpringTestCase extends AbstractTransactionalJUnit4SpringContextTests {
	
	protected String[] springXmlPath() {
		return new String[] { "classpath:spring/*.xml" };
	}
	
	@Before
	public void setup() {
			InstanceFactory.setInstanceProvider(new SpringProvider(
					springXmlPath()));
	}
	
	/**
	 * 提供给子类方面的取得Spring bean的方法
	 * @param name
	 * @return
	 */
	protected Object getBean(String name) {
		return this.applicationContext.getBean(name);
	}
	/**
	 * 泛型方法
	 * 使用约定的name convention获取bean
	 * 有点类似于autoWireByName, 使用类名首字母小写作为命名约定
	 * 使用此方法在子类中不用强制类型转换了，更加方便
	 * @param <T>
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected <M> M getBean(Class<M> clazz) {
		String clzName = clazz.getSimpleName();
		//use the name convertion
		String bName = clzName.substring(0,1).toLowerCase() + clzName.substring(1);
		return (M) this.applicationContext.getBean(bName);
	}

    @Resource(name = "dataSource")
    public void setDataSource(DataSource dataSource) {
        // TODO Auto-generated method stub
        super.setDataSource(dataSource);
    }
}
